<template>
  <div class="container">
    <!-- 左边的布局 -->
    <div class="container-left">
      <div class="container-left-outBox">
        <img :src="songDetails.al.picUrl" alt="11" />
        <div class="online-button">下载这首歌</div>
      </div>
    </div>
    <!-- 右边的布局 -->
    <div class="container-right">
      <div class="song-detail-box">
        <div class="song-title">{{ songDetails.name }}</div>
        <div class="song-content">
          <span class="song-jdk"
            >专辑:&nbsp;&nbsp;&nbsp;{{ songDetails.al.name }}</span
          >
          
          <span>歌手:&nbsp;&nbsp;&nbsp;{{ songDetails.ar[0].name }}</span>
        </div>
        <div class="song-words-box">
          <div class="song-inner" :style="`transform:translateY(-${songWordMove}px)`">
            <p v-for="(item,index) in songwordList" :key="index">{{item}}</p>

          </div>
        </div>
      </div>
    </div>
    <!-- 底部的控制条 -->
    <div class="control-bar">
      <div class="control-bar-inner">
        <div class="open">
          <span
            class="iconfont icon-shangyishou bian"
            @click="changeSongBtn('per')"
          ></span>
          <span
            class="iconfont icon-zantingtingzhi center"
            v-show="isPlay"
            @click="pauseSong"
          ></span>
          <span
            class="iconfont icon-bofangyinle center"
            v-show="!isPlay"
            @click="playSong"
          ></span>
          <span
            class="iconfont icon-xiayishou1 bian"
            @click="changeSongBtn('next')"
          ></span>
        </div>
        <img :src="songDetails.al.picUrl" alt="11" />
        <!-- 进度条那一块 -->
        <div class="move-bar-container">
          <div class="top">
            <span>{{ songDetails.name }}</span>
            <span>{{ currentTime }}/</span>
            <span>{{ totalTime }}</span>
          </div>
          <div class="bar" @click.stop="clickBar">
            <div class="beijing-chao">
              <div class="jing-du-tiao" :style="`width:${jingDuTiao}%`">
                <div class="xiao-dian-dian" @mousedown="mousedown"></div>
              </div>
            </div>
          </div>
        </div>
        <!-- 右侧分享等 -->
        <div class="right-buttons">
          <span class="iconfont icon-shengyin"></span>
          <span class="iconfont icon-qiehuan"></span>
          <span class="iconfont icon-xiazai"></span>
          <span class="iconfont icon-fenxiang"></span>
          <div class="liebiao" @click="openList" data-tag="flag">
            <span class="iconfont icon-liebiao" data-tag="flag"></span>
            <span class="num" data-tag="flag">{{ showSongList.length }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="dialog" v-show="isShowDislog" data-tag="flag">
      <div class="dialog-header" data-tag="flag">
        <span data-tag="flag">播放列表/{{ showSongList.length }}</span>
        <div class="ialog-header-right" data-tag="flag">
          <span class="iconfont icon-lajitong" data-tag="flag"></span>
          <span data-tag="flag">|</span>
          <span class="iconfont icon-delete"></span>
        </div>
      </div>
      <div class="song-list" data-tag="flag">
        <div
          :class="['song-item', item.id === currentId ? 'isClick' : '']"
          data-tag="flag"
          v-for="(item, index) in showSongList"
          :key="index"
          @click="palyThisSong(item.id)"
        >
          <span class="index" data-tag="flag">{{ index + 1 }}</span>
          <span class="song-title" data-tag="flag">{{ item.name }}</span>
          <div class="song-item-right" data-tag="flag">
            <span class="song-man" data-tag="flag">{{ item.ar[0].name }}</span>
            <span class="time" data-tag="flag">{{ item.totalTimes }}</span>
          </div>
        </div>
      </div>
    </div>
    <video :src="songUrl" id="song">歌曲</video>
  </div>
</template>

<script>
import { reqGetDetail } from '../../api/musicPlay';
import { reqGetSongUrl } from '../../api/musicPlay';
import { mapState, mapActions } from 'vuex';
import Moment from 'moment';
import { reqGetSongWord } from '../../api/songWord';

export default {
  name: "PlayAudio",
  data() {
    return {
      isPlay: false,
      isShowDislog: false,
      currentTime: '00:00',
      totalTime: '59:59',
      jingDuTiao: 0, //进度条
      // currentIndex: 0, //点击的songItem 和当前是第几首歌
      currentId: 0, //当前歌曲的id
      songList: [1819636482, 1332489492, 1493994313, 1362887830], //!应该把含歌曲id不含地址的列表放入vuex中

      songUrl: '', //歌的地址
      songDetails: {
        al: {},
        ar: [0],
      }, //歌的详情,防止报undefined
      showSongList: [], //展示播放歌曲
      songwordList: '', //歌词列表
      songWordMove:''//歌词位移
    };
  },

  methods: {
    ...mapActions('musicPlay', ['addSong']),
    //!歌词滚动的逻辑
    songWordScroll() {
      // 手写节流
      this.TimeGap = +new Date() - this.times;
      if (this.TimeGap < 2000 && this.TimeGap) return;
      this.times = +new Date();

      // const outBoxHeight = document.querySelector('.song-words-box');
      const innerBoxHeight = document.querySelector('.song-inner');
      //transform 版
      this.songWordMove = ((innerBoxHeight.offsetHeight-550) * this.jingDuTiao) / 100

      // scroll 版     
      // outBoxHeight.scrollTo(
      //   0,
      //   (innerBoxHeight.offsetHeight * this.jingDuTiao) / 100
      // );
    },
    //!列表点歌
    palyThisSong(id) {
      this.currentId = id;
      this.$nextTick(() => {
        this.isPlay = true;
        const oSong = document.querySelector('#song');
        oSong.play();
      });
    },
    //!切歌
    changeSongBtn(data) {
      const { currentId, songList } = this;

      const index = songList.findIndex((item) => {
        return item === currentId;
      });
      //!下一首
      if (data === 'next') {
        if (index === songList.length - 1) {
          this.currentId = songList[0];
        } else {
          this.currentId = songList[index + 1];
        }
        //!上一首
      } else {
        if (index === 0) {
          this.currentId = songList[songList.length - 1];
        } else {
          this.currentId = songList[index - 1];
        }
      }
      this.isPlay = true;
    },
    //!鼠标抬起的回调
    handlerMouseUp() {
      document.documentElement.removeEventListener(
        'mousemove',
        this.handlerMouseMove
      );
      this.isMove = false; //是否在移动
      document.documentElement.removeEventListener(
        'mouseup',
        this.handlerMouseUp
      );
    },
    //!鼠标移动的回调
    handlerMouseMove(e) {
      document.documentElement.addEventListener('mouseup', this.handlerMouseUp);
      const oBar = document.querySelector('.bar');
      const barWidth = oBar.offsetWidth;
      const barLift = oBar.getBoundingClientRect().left;
      // console.log(barWidth, barLift, e.clientX);
      // 设置进度条位置
      this.jingDuTiao = ((e.clientX - barLift) / barWidth) * 100 + 2;
    },
    //!拖拽进度条
    mousedown() {
      //最外面为点击事件
      this.isMove = true; //是否在移动
      //防止直接在小点点上抬起,不触发mouseup
      document.documentElement.addEventListener('mouseup',this.handlerMouseUp)
      document.documentElement.addEventListener(
        'mousemove',
        this.handlerMouseMove
      );
    },
    //!点击调进度
    clickBar(e) {
      const oSong = document.querySelector('#song');
      const oBar = document.querySelector('.bar');
      const barWidth = oBar.offsetWidth;
      const barLift = oBar.getBoundingClientRect().left;
      // 设置进度条位置
      this.jingDuTiao = ((e.clientX - barLift) / barWidth) * 100 + 2;
      // 设置播放位置
      oSong.currentTime = (this.jingDuTiao * this.dt) / 100000;
    },
    //!点击暂停
    pauseSong() {
      this.isPlay = false;
      const oSong = document.querySelector('#song');
      oSong.pause();
    },
    //!点击播放
    playSong() {
      this.isPlay = true;
      const oSong = document.querySelector('#song');
      oSong.play();
    },
    //!监听事件
    addEvent() {
      const oSong = document.querySelector('#song');
      oSong.addEventListener('timeupdate', () => {
        this.songWordScroll();
        // throttle失败用法
        // throttle(()=>{
        //   const outBoxHeight = document.querySelector('.song-words-box');
        //   const innerBoxHeight = document.querySelector('.song-inner');
        //   console.log(1112)
        //   outBoxHeight.scrollTo( 0,(innerBoxHeight.offsetHeight * this.jingDuTiao) / 100);
        // }, 1000);
        //进度条 开始时间动起来
        if (this.isMove) {
          return; //在移动的时候不监听
        }

        this.jingDuTiao = ((oSong.currentTime * 1000) / this.dt) * 100;
        this.currentTime = Moment(oSong.currentTime * 1000).format('mm:ss');
      });
      //播放完成时自动播放下一首
      oSong.addEventListener('ended', () => {
        this.changeSongBtn('next');
      });
    },
    // !获取歌曲详情
    getDetail() {},
    //!列表切换显示隐藏
    openList() {
      this.isShowDislog = !this.isShowDislog;
    },
    //!隐藏dialog
    hideDialog(e) {
      e.preventDefault();

      if (e.target.dataset.tag) {
        return;
      }
      this.isShowDislog = false;
    },
  },
  //!计算属性
  computed: {
    ...mapState('musicPlay', ['songIds', 'currentSongId']),
  },
  async mounted() {
    //处理query参数
    const { id } = this.$route.query;
    const flag = this.songList.some((item) => {
      return item === id;
    });
    if (id && !flag) {
      this.songList.unshift(+id);
    }
    this.currentId = this.songList[0];
    //调用监听事件
    this.addEvent();
    document.documentElement.addEventListener('click', this.hideDialog, true);
  },
  beforeDestroy() {
    document.documentElement.removeEventListener(
      'click',
      this.hideDialog,
      true
    );
  },
  watch: {
    currentId: {
      async handler(newId) {
        if (!newId) return;
        console.log('newId', newId);
        // this.currentIndex = this.songList.findIndex((item) => {
        //   return item === newId;
        // });
        try {
          //获取歌曲详情
          reqGetDetail(newId).then((res) => {
            this.songDetails = res.songs[0];
            this.dt = this.songDetails.dt; //毫秒组成的总时长
            this.totalTime = Moment(this.songDetails.dt).format('mm:ss');
          });

          const songUrl = await reqGetSongUrl(newId);
          if (!songUrl.data[0].url) {
            alert('该歌曲为付费歌曲');
            this.changeSongBtn('next');
            return;
          }
          this.songUrl = songUrl.data[0].url;
          //!获取歌词

          const { data } = await reqGetSongWord(newId);
          const index = data.lyric.indexOf('[00');
          const string = data.lyric.slice(index, -1);
          const arr = string.split('\n')
          const newArr = arr.map((item)=>{
            return item.slice(11)
          })
          this.songwordList = newArr;

          if (this.isPlay) {
            this.$nextTick(() => {
              const oSong = document.querySelector('#song');
              oSong.play();
            });
          }
        } catch (e) {
          console.log(e);
        }
      },
      immediate: true,
    },
    songList: {
      handler(newList) {
        const { showSongList } = this;
        if (!this.isNotFirst) {
          this.isNotFirst = true;
          newList.forEach((id) => {
            reqGetDetail(id).then((res) => {
              const songDetails = res.songs[0];

              songDetails.totalTimes = Moment(songDetails.dt).format('mm:ss');
              showSongList.push(songDetails);
            });
          });
        } else {
          reqGetDetail(newList[0]).then((res) => {
            const songDetails = res.songs[0];
            songDetails.totalTimes = Moment(songDetails.dt).format('mm:ss');
            showSongList.unshift(songDetails);
          });
        }
      },
      immediate: true,
    },
  },
};
</script>

<style  scoped>
.song-list {
  width: 100%;
  height: 100%;
  padding-left: 10px;
  overflow-y: scroll;
}
.song-list::-webkit-scrollbar {
  display: none;
}
.dialog {
  position: fixed;
  right: 160px;
  bottom: 80px;
  width: 480px;
  height: 410px;
  cursor: pointer;
  background-color: #2f343b;
  color: #727379;
}
.dialog-header {
  display: flex;
  justify-content: space-between;
  height: 50px;
  line-height: 50px;
  background-color: #2a2e35;
}
.dialog-header > span {
  padding-left: 25px;
}
.ialog-header-right {
  margin-right: 25px;
}
.ialog-header-right span {
  padding-left: 8px;
}
.song-item {
  width: 470px;
  height: 39px;
  display: flex;
}
.song-item:hover {
  background-color: #40444b;
}
.dialog .isClick {
  background-color: #40444b;
}
.song-item .index {
  display: block;
  width: 31px;
  height: 39px;
  line-height: 39px;
}
.song-item .song-title {
  width: 254px;
  height: 39px;
  line-height: 39px;
  color: #fff;
  /* white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden; */
}
.song-item-right {
  display: flex;
}
.song-item-right .song-man {
  display: block;
  width: 90px;
  height: 39px;
  line-height: 39px;
}
.song-item-right .time {
  display: block;
  width: 60px;
  height: 39px;
  line-height: 39px;
}
.iconfont:hover {
  text-shadow: 1px 1px 1px #fff, 1px 1px 1px #fff, 1px 1px 1px #fff,
    1px 1px 1px #fff;
  cursor: pointer;
}
.container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  background-image: linear-gradient(to right, #243949 0%, #517fa4 100%);
}

/* 左边的布局 */
.container-left {
  float: left;
  width: 45%;
  height: 100%;
  position: relative;
}
.container-left-outBox {
  position: absolute;
  right: 60px;
  top: 10px;
  width: 262px;
}
.container-left-outBox img {
  display: block;
  width: 260px;
  height: 260px;
  margin: 0 auto;
  margin-top: 10px;
}
.container-left-outBox .online-button {
  margin: 20px auto 0;

  width: 230px;
  height: 50px;
  border: 2px solid #fff;
  border-radius: 30px;
  text-align: center;
  line-height: 50px;
  color: #fff;
  font-size: 20px;
}
/* 右边的布局 */
.container-right {
  float: right;
  width: 55%;
  height: 100%;
}
.song-detail-box {
  margin-left: 40px;
  height: 100%;
  color: #fff;
}
.song-detail-box .song-title {
  height: 35px;
  font-size: 24px;
  line-height: 35px;
}
.song-detail-box .song-content {
  display: flex;
  margin-top: 9px;
  height: 24px;
  font-size: 15px;
  line-height: 24px;
}
.song-detail-box .song-content .song-jdk {
  display: inline-block;
  width: 230px;
  padding-right: 28px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.song-words-box {
  width: 420px;
  height: 420px;
  /* background-color: #544a8b; */
  font-size: 15px;
  overflow-y: scroll;
  transition: 1s;
}
.song-words-box::-webkit-scrollbar {
  display: none;
}
.control-bar {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 100%;
  height: 80px;
  background-color: #023a64;
}
.control-bar-inner {
  display: flex;
  align-items: center;
  margin: 0 auto;
  width: 960px;
  height: 100%;
}
.control-bar-inner .open {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 160px;
  height: 80px;
  color: #fff;
  font-size: 0;
  margin-right: 36px;
}
.control-bar-inner .bian {
  display: flex;
  font-size: 40px;
  margin-bottom: 7px;
}
.control-bar-inner .icon-xiayishou1 {
  margin-bottom: 0px;
}
.control-bar-inner .center {
  font-size: 49px;
  line-height: 80px;
}
.control-bar-inner img {
  width: 60px;
  height: 60px;
}
.move-bar-container {
  width: 371px;
  height: 100%;
  margin-left: 20px;
  margin-right: 36px;
}
.move-bar-container .top {
  padding-bottom: 12px;
  padding-top: 18px;
  font-size: 13px;
  display: flex;
  font-size: 13px;
  color: #fff;
}
.move-bar-container .top span:nth-child(1) {
  display: block;

  width: 290px;
}
.move-bar-container .bar {
  width: 371px;
  height: 12px;

  display: flex;
  align-items: center;
}
.move-bar-container .bar .beijing-chao {
  width: 100%;
  height: 3px;
  background-color: #5e5364;
}
.move-bar-container .bar .beijing-chao .jing-du-tiao {
  height: 3px;
  background-color: #11a4f0;
  position: relative;
}
.xiao-dian-dian {
  background: #fff;
  height: 12px;
  width: 12px;
  border-radius: 50%;
  position: absolute;
  right: 0px;
  top: -4px;
}
.xiao-dian-dian:hover {
  height: 14px;
  width: 14px;
}
.right-buttons {
  display: flex;
  align-items: center;
  color: #fff;
  height: 100%;
  width: 260px;
  font-size: 18px;
  cursor: pointer;
}
.right-buttons > span {
  padding-right: 25px;
}
.right-buttons .liebiao {
  width: 60px;
  height: 23px;
  background: #082d38;
  margin-left: 15px;
  border-radius: 15px;
  display: flex;
  align-items: center;
}
.right-buttons .liebiao .icon-liebiao {
  padding-left: 10px;
}
.right-buttons .liebiao .num {
  font-size: 16px;
}
</style>